<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2021-06-09
 * Time: 16:17:38
 * Info:
 */

namespace app\common\model;

use app\common\service\admin\AuthService;

class AuthGroup extends TimeInit
{

    /**
     * 获取角色组的名字和id
     * @return mixed
     */
    public static function getRoleGroup()
    {
        $list = self::where(['status' => 'normal'])->column('name', 'id');

        return $list;
    }

    /**
     * 根据角色ID获取授权节点
     *
     * @param $authId
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAuthorizeNodeListByAdminId($checkNodeList)
    {
        $pk    = "id";
        $pid   = "pid";
        $root  = 0;
        $child = "children";

        $list         = AuthRule::field('id,node,title,type,is_auth,pid')->order('id asc,node asc')->select()->toArray();
        $checkNodeArr = [];
        if ($checkNodeList != '*') {
            $checkNodeArr = explode(",", $checkNodeList);
        }
        foreach ($list as $key => $v) {
            $list[$key]['field']   = 'node';
            $list[$key]['spread']  = true;
            $list[$key]['checked'] = in_array($v['id'], $checkNodeArr) ? true : false;
        }

        $newNodeList = [];

        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                $list[$key]['title'] = "{$data['title']}【{$data['node']}】";
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $newNodeList[] =& $list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent           =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                    }
                }
            }

        }

        return $newNodeList;
    }

    /**
     * 根据管理员id获取管理员对应的角色组名称
     * @return array
     */
    public static function getAdminGroupNamesById($adminId)
    {
        $libAuth = new AuthService();
        $roleId  = $libAuth->getGroups($adminId);
        if ($roleId->isEmpty()) {
            return [];
        } else {
            $roleId = $roleId->toArray();

            return array_column($roleId, 'name');
        }
    }

}
